#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "SDL.h"
#include "SDL_ttf.h"

//#define FONT "/Library/Fonts/VeraMono.ttf"
//#define SIZE 9
//#define PAD 1
//
//#define START 32
//#define END 126
//
//#define WIDTH 128
//#define HEIGHT 128

static void print_metrics(TTF_Font *font, int index, int tx, int ty, int w, int h)
{
	int gx, gy, advance;
	TTF_GlyphMetrics(font, index, &gx, NULL, &gy, NULL, &advance);
	
	printf("%d %d %d %d %d %d %d %d\n", index, gx, gy, tx, ty, w, h, advance);
}

int main(int argc, char *argv[])
{
	if(argc != 6){
		printf("makefont font size padding width height\n");
		return -1;
	}
	
	char *FONT = argv[1];
	int SIZE = atoi(argv[2]);
	int PAD = atoi(argv[3]);
	int WIDTH = atoi(argv[4]);
	int HEIGHT = atoi(argv[5]);
	
	SDL_Color white = {0xFF, 0xFF, 0xFF, 0};
	SDL_Color black = {0x00, 0x00, 0x00, 0};
		
	if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) {
		fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
		return(2);
	}

	if ( TTF_Init() < 0 ) {
		fprintf(stderr, "Couldn't initialize TTF: %s\n",SDL_GetError());
		SDL_Quit();
		return(2);
	}

	TTF_Font *font = TTF_OpenFont(FONT, SIZE);
	if ( font == NULL ) {
		fprintf(stderr, "Could not load font\n");
		return -1;
	}
//	TTF_SetFontStyle(font, TTF_STYLE_NORMAL | TTF_STYLE_BOLD | TTF_STYLE_ITALIC | TTF_STYLE_UNDERLINE);

	SDL_Surface *output = SDL_CreateRGBSurface(SDL_SWSURFACE, WIDTH, HEIGHT, 32, 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff);
	SDL_FillRect(output, NULL, SDL_MapRGB(output->format, 0, 0, 0));
	
	printf("%d %d, %d, %d\n", PAD, TTF_FontLineSkip(font), TTF_FontAscent(font), TTF_FontDescent(font));

	int y = PAD;
	int x = PAD;
	int maxh = 0;
	
	int i;
	for(i = 32; i <= 126; i++ ) {
		SDL_Surface *glyph = TTF_RenderGlyph_Shaded( font, i, white, black);
		
		if(x + glyph->w + PAD*2 > WIDTH){
			x = PAD;
			
			y += maxh + PAD*2;
			maxh = 0;
		}
		
		SDL_Rect rect = (SDL_Rect){x, HEIGHT - y - glyph->h, glyph->w, glyph->h};
		SDL_BlitSurface(glyph, NULL, output, &rect);
		print_metrics(font, i, x, y, glyph->w, glyph->h);
		
		if(glyph->h > maxh) maxh = glyph->h;
		x += glyph->w + PAD*2;
	}
	
	SDL_SaveBMP(output, "font.bmp");
	
	return 0;
}
